package com.daikin.ktmustwrite.ui.fragment.tree

import android.os.Bundle
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ConvertUtils
import com.daikin.ktmustwrite.R
import com.daikin.ktmustwrite.app.base.BaseFragment
import com.daikin.ktmustwrite.app.ext.init
import com.daikin.ktmustwrite.app.ext.loadServiceInit
import com.daikin.ktmustwrite.app.ext.showError
import com.daikin.ktmustwrite.app.ext.showLoading
import com.daikin.ktmustwrite.app.weight.recycleview.SpaceItemDecoration
import com.daikin.ktmustwrite.databinding.IncludeListBinding
import com.daikin.ktmustwrite.ui.adapter.SystemAdapter
import com.daikin.ktmustwrite.viewmodel.request.RequestTreeViewModel
import com.daikin.ktmustwrite.viewmodel.state.TreeViewModel
import com.kingja.loadsir.core.LoadService
import kotlinx.android.synthetic.main.include_recyclerview.*

class SystemFragment : BaseFragment<TreeViewModel, IncludeListBinding>() {
    private lateinit var loadsir:LoadService<Any>
    private val systemAdapter:SystemAdapter by lazy { SystemAdapter(arrayListOf()) }
    private val requestTreeViewModel:RequestTreeViewModel by viewModels()

    override fun layoutId(): Int {
        return R.layout.include_list
    }

    override fun initView(savedInstanceState: Bundle?) {
        loadsir= loadServiceInit(swipeRefresh){
            loadsir.showLoading()
            requestTreeViewModel.getSystemData()
        }
        recyclerView.init(LinearLayoutManager(context),systemAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, ConvertUtils.dp2px(8f)))
        }
        swipeRefresh.init {
            requestTreeViewModel.getSystemData()
        }
        systemAdapter.run {

        }
    }

    override fun lazyLoadData() {
        loadsir.showLoading()
        requestTreeViewModel.getSystemData()
    }

    override fun createObserver() {
        requestTreeViewModel.systemDataState.observe(viewLifecycleOwner, Observer {
            swipeRefresh.isRefreshing = false
            if (it.isSuccess) {
                loadsir.showSuccess()
                systemAdapter.setList(it.listData)
            } else {
                loadsir.showError(it.errMessage)
            }
        })

    }
}